<?php

namespace App\Model;


use Illuminate\Support\Facades\Log;

class GiftSpec extends BaseModel
{
    protected $table = 'gift_spec';
    protected $primaryKey = 'spec_id';
    public $timestamps = false;
    protected $fillable = ['spec_num','is_show'];
    
    public function setSpecNum($data=[]){
        if(empty($data)) return true;
        $old = self::get(['spec_num','spec_id'])->toArray();
        // 新增
        if(empty($old)){
            foreach ($data as $value) {
                GiftSpec::create(['spec_num' => $value,'is_show' => 1]);
            }
            return true;
        }
        
        $oldGroup = array_column($old,'spec_num','spec_id');
        
        // 新增
        foreach ($diffData = array_diff($data, $oldGroup) as $value) {
            GiftSpec::create(['spec_num' => $value,'is_show' => 1]);
        }
    
        // 更新
        foreach ($diffData = array_diff($oldGroup, $data) as $key => $value) {
            GiftSpec::where(['spec_id' => $key])->update(['spec_num' => $value,'is_show' => 0]);
        }
    
        // 交集
        foreach ($intersectData = array_intersect($oldGroup,$data) as $key => $value){
            GiftSpec::where(['spec_id' => $key])->update(['spec_num' => $value,'is_show' => 1]);
        }
        return true;
    }
    
    public function getSpecNums(){
        $giftSpecModel = new GiftSpec();
        $result = $giftSpecModel->where(['is_show' => 1])->get(['spec_num'])->toArray();
        if(empty($result)) return '';
        return implode(',',array_column($result,'spec_num'));
    }
}
